<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="filter-container">
        <el-form v-show="showSearch" ref="filterFormRef" :model="filterForm"
                 :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="组织名称" prop="orgName">
            <el-input
              v-model="filterForm.orgName"
              placeholder="请输入组织名称"
              clearable
              size="small"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item label="组织编码" prop="orgCode">
            <el-input
              v-model="filterForm.orgCode"
              placeholder="请输入组织编码"
              clearable
              size="small"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <div>
          <div class="flex-1" />
          <div style="display:flex;">
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['ORGMANAGE_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >新增</el-button>
          <el-button
            v-permission="['ORGMANAGE__CLOSEALL_BUTTON']"
            icon="el-icon-folder"
            @click="onFoldAll"
          >折叠全部</el-button>
          <div class="flex-1" />
          <dt-dialog-column v-model="isShowTable" :columns="columns" :table-ref="$refs.table"
                            @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          border
          :header-cell-style="{ backgroundColor: '#f2f2f2'}"
          :data="tableData"
          row-key="orgId"
          lazy
          :load="load"
          :default-expand-all="false"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :expand-row-keys="expandRowKeys"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <!-- <el-table-column fixed="left" type="selection" width="55" align="center" /> -->
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="(index)=> index + 1"
          />
          <el-table-column v-if="columns[0].show" key="orgName" label="组织名称"
                           show-overflow-tooltip align="left" prop="orgName" />
          <el-table-column v-if="columns[1].show" key="orgCode" label="组织编码"
                           show-overflow-tooltip align="center" prop="orgCode" />
          <el-table-column v-if="columns[2].show" key="orgLevel" label="组织层级"
                           show-overflow-tooltip align="center" prop="orgLevel">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.orgLevel" :value="scope.row.orgLevel" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[3].show" key="orgCategory" label="部门类别"
                           show-overflow-tooltip align="center" prop="orgCategory">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.orgType" :value="scope.row.orgCategory" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[4].show" key="orgSort" label="排序"
                           show-overflow-tooltip align="center" prop="orgSort" />
          <el-table-column v-if="columns[5].show" key="createTime" label="创建时间"
                           show-overflow-tooltip align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" label="操作" fixed="right"
                           align="center" class-name="small-padding fixed-width" width="360">
            <template slot-scope="scope">
              <el-button
                v-permission="['ORGMANAGE_UPDATE_BUTTON']"
                size="small"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="small"
                @click="handleDetail(scope.row)"
              >查看</el-button>
              <el-button
                v-permission="['ORGMANAGE_ADDCHILDREN_BUTTON']"
                size="small"
                @click="onAddChildren(scope.row)"
              >新增下级</el-button>
              <el-button
                v-permission="['ORGMANAGE_DEL_BUTTON']"
                size="small"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <dt-pagination
          v-show="total>0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 详情弹框 -->
    <OrgEdit ref="orgForm" />
  </div>
</template>

<script>
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import OrgEdit from './components/orgEdit.vue'
import hrOrganizationApi from '@/framework/api/userCenter/hrOrganization'

export default {
  name: 'OrgManage',
  components: { OrgEdit },
  mixins: [dialogColumn],
  dicts: ['orgLevel', 'orgType'],
  data() {
    return {
      loading: false,
      isShowTable: true,
      columns: [
        { prop: 'orgName', label: '组织名称', show: true },
        { prop: 'orgCode', label: '组织编码', show: true },
        { prop: 'orgLevel', label: '组织层级', show: true },
        { prop: 'orgCategory', label: '部门类别', show: true },
        { prop: 'orgSort', label: '排序', show: true },
        { prop: 'createTime', label: '创建时间', show: true }
      ],
      showSearch: true,
      total: 0,
      tableData: [],
      filterForm: {
        orgName: '',
        orgCode: ''
      },
      expandRowKeys: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList(newParentOrgId, oldParentOrgId) {
      this.loading = true
      if (this.filterForm.orgName != '' || this.filterForm.orgCode != '') { // 带参数分页
        hrOrganizationApi.pageList(this.filterForm).then((res) => {
          this.loading = false
          this.tableData = res.data.rows
          this.total = res.data.totalRows
        })
      } else { // 不带参数tree
        this.total = 0
        if (newParentOrgId && newParentOrgId !== 0) {
          hrOrganizationApi.listByDataScope({ orgId: newParentOrgId }).then((res) => {
            let currentArea = []
            currentArea = res.data.map((item, index) => {
              item.hasChildren = true
              return item
            })
            const { store } = this.$refs.table
            // 顶部不能选根节点  不需要判断parentId是否为0
            const parent = store.states.lazyTreeNodeMap[newParentOrgId]
            // 判断是否展开子节点  若未展开parent为空
            if (parent) {
            // 改变原数组处理parent 待优化
              parent.splice(0, parent.length, ...currentArea)
              if (oldParentOrgId) {
                hrOrganizationApi.listByDataScope({ orgId: oldParentOrgId }).then((oldRes) => {
                  this.$set(store.states.lazyTreeNodeMap, oldParentOrgId, oldRes.data)
                  setTimeout(() => {
                    if (store.states.treeData[oldParentOrgId]) store.states.treeData[oldParentOrgId].expanded = true
                  }, 0)
                })
              }
            } else {
              // 如果父节点无法在lazyTreeNodeMap中查到  即parent为空 则刷新当前父节点  并且展开子节点
              if (newParentOrgId === '-1') {
                // 根组织特殊处理
                this.tableData = res.data
              } else {
                this.$set(store.states.lazyTreeNodeMap, newParentOrgId, res.data)
                setTimeout(() => {
                  if (store.states.treeData[newParentOrgId]) store.states.treeData[newParentOrgId].expanded = true
                }, 0)
                if (oldParentOrgId) {
                  hrOrganizationApi.listByDataScope({ orgId: oldParentOrgId }).then((oldRes) => {
                    this.$set(store.states.lazyTreeNodeMap, oldParentOrgId, oldRes.data)
                    // store.states.treeData[oldParentOrgId] ? store.states.treeData[oldParentOrgId].expanded = true : ''
                  })
                }
              }
            }
            this.loading = false
          })
        } else {
          hrOrganizationApi.listByDataScope({ orgId: 0 }).then((res) => {
            if (res.success) {
              this.tableData = res.data.map((item, index) => {
                item.hasChildren = true
                item.children = []
                return item
              })
            }
            this.loading = false
          })
        }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        userOrgId: null,
        userId: null,
        orgId: null,
        orgSort: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        updateUser: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleFilter() {
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('filterFormRef')
      this.handleFilter()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.orgForm.openOrg(row, 'update')
    },
    handleDetail(row) {
      this.$refs.orgForm.openOrg(row, 'detail')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${row.orgName}”吗?`, type: 'warning' }).then(() => {
        hrOrganizationApi.delete({ orgId: row.orgId }).then((res) => {
          this.$refs.orgForm.initTree()
          this.getList(row.orgParentId)
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {
        // 取消不做操作
        })
      })
    },
    // 折叠所有并初始化列表
    onFoldAll() {
      const { treeData } = this.$refs.table['store'].states
      for (const i in treeData) {
        treeData[i].loaded = false
        treeData[i].expanded = false
      }
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      hrOrganizationApi.listByDataScope({ orgId: tree.orgId }).then((res) => {
        if (res.data.length && res.data.length > 0) {
          const data = res.data.map((item, index) => {
            item.hasChildren = true
            item.children = []
            return item
          })
          resolve(data)
        } else {
          tree.hasChildren = false
        }
      })
    },
    // 点击新增组织按钮
    handleAdd() {
      this.$refs.orgForm.openOrg('', 'add')
    },
    // 点击新增下级组织按钮
    onAddChildren(row) {
      this.$refs.orgForm.openOrg(row, 'addChildren')
      this.$set(row, 'hasChildren', true)
    }
  }
}
</script>
